'use client'
import SliderCaptcha from 'rc-slider-captcha'
import React, { useRef } from 'react'
import { sleep } from 'ut2'
import createPuzzle from 'create-puzzle'
import {
  RubyOutlined,
  MehOutlined,
  SmileOutlined,
  RedoOutlined,
  LoadingOutlined
} from '@ant-design/icons'

type SolidCaptchaProps = {
  onSuccess?: () => void
  onError?: () => void
}

const SolidCaptcha = (params: SolidCaptchaProps) => {
  const offsetXRef = useRef(0) // x 轴偏移值
  // 查看是否在安全距离
  const verifyCaptcha = async (data: { x: number }) => {
    await sleep()
    if (data.x >= offsetXRef.current - 5 && data.x < offsetXRef.current + 5) {
      params?.onSuccess?.()
      return Promise.resolve()
    } else {
      params?.onError?.()
    }
    return Promise.reject()
  }
  return (
    <div className="container">
      <SliderCaptcha
        request={() =>
          createPuzzle(
            'https://files.superbed.cn/proxy/7468686c6f2633336b776c74736873327f7872327e7f797e736f327f737133257a292d2c7a7e2f2c7a2e28282e7d2b792c7879292b7f7d7f2d282f7d78287e782c2d2f2c2e242432766c7b.png'
          ).then(res => {
            offsetXRef.current = res.x
            return {
              // 背景图片
              bgUrl: res.bgUrl,
              // 核验区域
              puzzleUrl: res.puzzleUrl
            }
          })
        }
        onVerify={data => {
          return verifyCaptcha(data)
        }}
        bgSize={{ width: 462, height: 266 }}
        tipIcon={{
          default: <RubyOutlined />,
          loading: <LoadingOutlined />,
          success: <SmileOutlined />,
          error: <MehOutlined />,
          refresh: <RedoOutlined />
        }}
        tipText={{
          default: '向右👉拖动完成拼图',
          loading: '👩🏻‍💻🧑‍💻努力中...',
          moving: '向右拖动至拼图位置',
          verifying: '验证中...',
          error: '验证失败',
          success: '验证通过'
        }}
      />
    </div>
  )
}

export default SolidCaptcha
